package com.ddpt.permission.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lh.center.common.enums.MarketingApp;
import com.lh.center.common.util.AssertUtil;
import com.lh.center.common.util.IdUtil;
import com.lh.center.extensions.api.global.dubbo.DubboGlobalConfigService;
import com.lh.center.permission.QRCodeStatusEnum;
import com.lh.center.permission.api.entity.MerchantAdminUser;
import com.lh.center.permission.api.entity.StoreAdminUser;
import com.lh.center.permission.dto.GetBindQRCodeDto;
import com.lh.center.permission.dto.WXBindDto;
import com.lh.center.permission.dto.WXUnBindDto;
import com.lh.center.permission.service.MerchantAdminUserService;
import com.lh.center.permission.service.StoreAdminUserService;
import com.lh.center.permission.util.WXLoginUtil;
import com.lh.center.permission.vo.GetBindQRCodeStatusVo;
import com.lh.center.permission.vo.GetBindQRCodeVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * 微信绑定
 */
@RestController
@RequestMapping("/api/permission/login/wx")
public class WxBindController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private WXLoginUtil wxLoginUtil;

    @Resource
    private MerchantAdminUserService merchantAdminUserService;

    @Resource
    private StoreAdminUserService storeAdminUserService;

    @DubboReference
    private DubboGlobalConfigService dubboGlobalConfigService;

    //绑定微信二维码缓存前缀
    private static final String BIND_CODE = "BIND_CODE";

    //请求地址拼接的参数
    private static final String appendParams = "/merchant/#/bind_wechat_mobile";

    //商家地址拼接
    private static final String storeAppendParams = "/store/#/bind_wechat_mobile";

    /**
     * 生成绑定微信二维码
     */
    @PostMapping("/getBindQRCode")
    public GetBindQRCodeVo getBindQRCode(@RequestBody GetBindQRCodeDto dto) {
        String code = IdUtil.nextId().toString();
        stringRedisTemplate.opsForValue().set(BIND_CODE + code, QRCodeStatusEnum.wait.name(), 3, TimeUnit.MINUTES);
        GetBindQRCodeVo vo = new GetBindQRCodeVo();
        String host = "";
        if (dto.getApp() == MarketingApp.store){
            host = dubboGlobalConfigService.getGlobalHost().getHost() + storeAppendParams + "?tag=" + code + "&userId=" + dto.getUserId();
        } else if (dto.getApp() == MarketingApp.merchant){
            host = dubboGlobalConfigService.getGlobalHost().getHost() + appendParams + "?tag=" + code + "&userId=" + dto.getUserId();
        }
        //callBackUrl encode
        try {
            host = URLEncoder.encode(host,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = wxLoginUtil.getScanCodePrefixUrl().replace("{appId}", wxLoginUtil.getAppId())
                .replace("{callbackUrl}", host);
        vo.setQrCode(url);
        vo.setTag(code);
        vo.setUserId(dto.getUserId());
        return vo;
    }

    /**
     * 轮询获取二维码状态
     */
    @PostMapping("/getBindQRCodeStatus")
    public GetBindQRCodeStatusVo getBindQRCodeStatus(@RequestBody GetBindQRCodeVo dto) {
        String codeStatus = stringRedisTemplate.opsForValue().get(BIND_CODE + dto.getTag());
        AssertUtil.isEmpty(codeStatus, "二维码已失效");
        GetBindQRCodeStatusVo vo = new GetBindQRCodeStatusVo();
        vo.setStatus(codeStatus);
        return vo;
    }


    /**
     * 绑定微信
     */
    @PostMapping("/bind")
    public void bind(@RequestBody WXBindDto dto){
        AssertUtil.isEmpty(dto.getWxCode(),"未携带微信code");
        AssertUtil.isEmpty(dto.getUserId(),"未携带登陆userId");
        String codeStatus = stringRedisTemplate.opsForValue().get(BIND_CODE + dto.getTag());
        AssertUtil.isEmpty(codeStatus, "二维码已失效");
        Long userId = Long.valueOf(dto.getUserId());

        if (dto.getApp() == MarketingApp.store ){
            StoreAdminUser user = storeAdminUserService.getById(userId);
            AssertUtil.isNull(user,"用户不存在");
            AssertUtil.isTrue(!ObjectUtils.isEmpty(user.getWxOpenId()) ,"已经绑定微信");
            //更新二维码状态
            stringRedisTemplate.opsForValue().set(BIND_CODE + dto.getTag(), QRCodeStatusEnum.scanned.name(), 3, TimeUnit.MINUTES);
            String openId = wxLoginUtil.getOpenId(dto.getWxCode());
            storeAdminUserService.bindWx(userId,openId);
        } else if (dto.getApp() == MarketingApp.merchant){
            MerchantAdminUser user = merchantAdminUserService.getMerchanAdminUser(userId);
            AssertUtil.isNull(user,"用户不存在");
            AssertUtil.isTrue(!ObjectUtils.isEmpty(user.getWxOpenId()) ,"已经绑定微信");
            //更新二维码状态
            stringRedisTemplate.opsForValue().set(BIND_CODE + dto.getTag(), QRCodeStatusEnum.scanned.name(), 3, TimeUnit.MINUTES);
            String openId = wxLoginUtil.getOpenId(dto.getWxCode());
            merchantAdminUserService.bindWx(userId, openId);
        }
        stringRedisTemplate.opsForValue().set(BIND_CODE + dto.getTag(), QRCodeStatusEnum.finished.name(), 3, TimeUnit.MINUTES);
    }

    /**
     * 解除绑定
     */
    @PostMapping("/unBind")
    public void unBind(@RequestBody WXUnBindDto dto){
        //AssertUtil.isEmpty(dto.getWxCode(),"未携带微信code");
        AssertUtil.isEmpty(dto.getUserId(),"未携带登陆userId");
        Long userId = Long.valueOf(dto.getUserId());
        if (dto.getApp() == MarketingApp.store){
            StoreAdminUser user = storeAdminUserService.getById(userId);
            AssertUtil.isNull(user,"用户不存在");
            AssertUtil.isTrue(ObjectUtils.isEmpty(user.getWxOpenId()) ,"未绑定微信");
            storeAdminUserService.unBindWx(userId);
        } else if (dto.getApp() == MarketingApp.merchant){
            MerchantAdminUser user = merchantAdminUserService.getMerchanAdminUser(userId);
            AssertUtil.isNull(user,"用户不存在");
            AssertUtil.isTrue(ObjectUtils.isEmpty(user.getWxOpenId()) ,"未绑定微信");
            merchantAdminUserService.unBindWx(userId);
        }

    }
}
